package com.zy.openchat.util;

import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.text.TextUtils;

import com.blankj.utilcode.util.SPUtils;
import com.google.gson.JsonObject;
import com.zy.openchat.App;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.user.MobileContactInfo;

import java.util.ArrayList;
import java.util.Map;

public class ContactUtils {


    private volatile static ContactUtils contactUtils;

    private ACache mACache;

    private ArrayList<MobileContactInfo> orignContactInfos;
    private final String KEY = "ContactInfos";

    private ContactUtils() {
        mACache = ACache.get(App.getInstanse());
        Object object = mACache.getAsObject(KEY);
        if(object!=null&&object instanceof ArrayList<?>){
            orignContactInfos = (ArrayList<MobileContactInfo>)object;
        }
    }

    public ArrayList<MobileContactInfo> getHasUserIdContactInfos(){
        ArrayList<MobileContactInfo> contactInfos = null;
        if(orignContactInfos!=null&&orignContactInfos.size()>0){
            for(MobileContactInfo contactInfo:orignContactInfos){
                if(contactInfo.user_id>0){
                    if(contactInfos==null){
                        contactInfos = new ArrayList<>();
                    }
                    contactInfos.add(contactInfo);
                }
            }
        }
        return contactInfos;
    }

    public MobileContactInfo getContactInfoByUserId(long userId){
        if(orignContactInfos!=null&&orignContactInfos.size()>0){
            for(MobileContactInfo contactInfo:orignContactInfos){
                if(contactInfo.user_id == userId){
                    return contactInfo;
                }
            }
        }
        return null;
    }

    public static ContactUtils getIntance() {
        if (contactUtils == null) {
            synchronized (ContactUtils.class) {
                if (contactUtils == null) {
                    contactUtils = new ContactUtils();
                }
            }
        }
        return contactUtils;
    }

    public boolean isSetting(){
        return SPUtils.getInstance().getBoolean("isSettingContack",false);
    }

    public void changeImportedContacts(Context context){
        if(!isSetting()){
            return;
        }
        ArrayList<MobileContactInfo> contacts = getAllContacts(context);
        if(contacts!=null&&contacts.size()>0){
            if(orignContactInfos!=null&&orignContactInfos.size()>0){
                ArrayList<MobileContactInfo> newContacts = new ArrayList();
                for(MobileContactInfo contactInfo:contacts){
                    boolean isFindSame = false;
                    for(MobileContactInfo orgin:orignContactInfos){
                        if(!TextUtils.isEmpty(contactInfo.phone_number)&&contactInfo.phone_number.equals(orgin.phone_number)){
                            isFindSame = true;
                            break;
                        }
                    }
                    if(!isFindSame){
                        newContacts.add(contactInfo);
                    }
                }
                contacts = newContacts;
            }
        }

        if(contacts!=null&&contacts.size()>0){
            final ArrayList<MobileContactInfo> inner = contacts;
            TelegramManager.getTelegramManager().changeImportedContacts(contacts, new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                    if(obj.ok){
                        if(orignContactInfos==null){
                            orignContactInfos = new ArrayList<>();
                        }
                        orignContactInfos.addAll(inner);
                        setContactInfos(orignContactInfos);
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {

                }
            });
        }

    }

    public void setContactInfos(ArrayList<MobileContactInfo> contactInfos){
        if(contactInfos==null){
            contactInfos = new ArrayList<MobileContactInfo>();
        }
        orignContactInfos = contactInfos;
        mACache.put(KEY,contactInfos);
        SPUtils.getInstance().put("isSettingContack",true);
    }

    public void clean(){
        SPUtils.getInstance().put("isSettingContack",false);
        orignContactInfos = null;
        mACache.put(KEY,new ArrayList<MobileContactInfo>());
    }


    public ArrayList<MobileContactInfo> getAllContacts(Context context) {
        ArrayList<MobileContactInfo> contacts = new ArrayList<MobileContactInfo>();

        Cursor cursor = context.getContentResolver().query(
                ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        while (cursor.moveToNext()) {
            //新建一个联系人实例
            MobileContactInfo temp = new MobileContactInfo();
            temp.user_id = 0;
            String contactId = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.Contacts._ID));
            //获取联系人姓名
            String name = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            temp.setName(name);

            //获取联系人电话号码
            Cursor phoneCursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
            while (phoneCursor.moveToNext()) {
                String phone = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                phone = phone.replace("-", "");
                phone = phone.replace(" ", "");
                temp.phone_number = phone;
            }

//            //获取联系人备注信息
//            Cursor noteCursor = context.getContentResolver().query(
//                    ContactsContract.Data.CONTENT_URI,
//                    new String[]{ContactsContract.Data._ID, ContactsContract.CommonDataKinds.Nickname.NAME},
//                    ContactsContract.Data.CONTACT_ID + "=?" + " AND " + ContactsContract.Data.MIMETYPE + "='"
//                            + ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE + "'",
//                    new String[]{contactId}, null);
//            if (noteCursor.moveToFirst()) {
//                do {
//                    String note = noteCursor.getString(noteCursor
//                            .getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME));
//                    temp.note = note;
//                    Log.i("note:", note);
//                } while (noteCursor.moveToNext());
//            }
            contacts.add(temp);
            //记得要把cursor给close掉
            phoneCursor.close();
//            noteCursor.close();
        }
        cursor.close();
        return contacts;
    }
}
